package com.example.common.utils;

import com.example.entity.domain.User;
import com.example.entity.vo.UserVo;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;
import java.util.Date;

public class JwtUtils {

    // 自动生成符合 HS512 要求的安全密钥（64字节）
    private static final Key SIGNING_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS512);

    // 密钥字符串（可用于日志打印、调试或配置文件中保存）
    private static final String SECRET_STRING = Base64.getEncoder().encodeToString(SIGNING_KEY.getEncoded());

    // 过期时间
    private static final long EXPIRATION = 86400000;

    // 生成 JWT
    public static String generateToken(User user) {
        return Jwts.builder()
                .setSubject(user.getUserName())
                .claim("userId", user.getId())
                .claim("userName", user.getUserName())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SIGNING_KEY,SignatureAlgorithm.HS512)
                .compact();
    }

    // 解析 JWT
    public static String parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_STRING)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    public static Jws<Claims> parserToken(String token){
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET_STRING).parseClaimsJws(token);
        return claimsJws;
    }

    public static UserVo getInfoFromToken(String token) {
        Jws<Claims> claimsJws = parserToken(token);
        Claims body = claimsJws.getBody();
        String userName = (String) body.get("userName");
        Long userId = Long.valueOf(String.valueOf(body.get("userId")));
        return new UserVo(userId, userName,null);
    }

    public static boolean validateToken(String token) {
        try {
            parseToken(token);
            return true;
        } catch (JwtException e) {
            return false;
        }
    }


    public static void invalidateToken(String token) {
        try {
            Claims claims = parserToken(token).getBody();
            claims.setExpiration(new Date(System.currentTimeMillis()));
            String compact = Jwts.builder()
                    .setClaims(claims)
                    .signWith(SIGNING_KEY, SignatureAlgorithm.HS512)
                    .compact();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
   